<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">所属单位</label>
        <el-select v-model="query.farm_id" filterable placeholder="请选择" style="width: 185px;" class="filter-item">
          <el-option
            v-for="item in dict.farms"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">数据类型</label>
        <el-select
          v-model="query.nannong_type"
          filterable
          placeholder="请选择"
          style="width: 185px;"
          class="filter-item"
        >
          <el-option v-for="item in dict.nannong_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="600px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="所属单位" prop="farm_id">
                <el-select v-model="form.farm_id" filterable placeholder="请选择" style="width: 250px;">
                  <el-option
                    v-for="item in dict.farms"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="数据类型" prop="nannong_type">
                <el-select v-model="form.nannong_type" filterable placeholder="请选择" style="width: 250px;">
                  <el-option
                    v-for="item in dict.nannong_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="数据日期">
                <el-date-picker v-model="form.create_date" type="date" style="width: 250px;" value-format="yyyy-MM-dd" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="图片">
                <el-upload
                  ref="upload"
                  list-type="picture-card"
                  class="upload-demo"
                  action="#"
                  :file-list="fileList"
                  :auto-upload="false"
                  :multiple="true"
                >
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过512kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="showImageViewer" height="80%" append-to-body>
        <img v-if="imageViewerId" width="100%" :src="baseApi+ '/api/v2/public/getImage?id=' +imageViewerId" alt="">
      </el-dialog>
      <!--表格渲染-->
      <el-row type="flex" justify="center" align="middle">
        <el-col class="image_wrap">
          <el-card
            v-for="(obj) in crud.data"
            :body-style="{ padding: '10px' }"
            class="imageCard"
            @click.native="cardClick(obj)"
          >
            <el-checkbox
              v-model="obj.selected"
              @change="selectedChange(obj)"
              @click.native.prevent="skipOption"
            ></el-checkbox>
            <el-image :src="baseApi + '/api/v2/public/getImage?id=' + obj.file_id" class="image" fit="contain" lazy @click.stop="handleShowImageViewer(obj.file_id)">
              <div slot="error" class="image-slot">
                <span>No Image</span>
              </div>
            </el-image>
            <div style="padding: 0px;">
              <div style="height: 18px;">
                <label class="detail_label">{{ obj.farm_name }}</label>
              </div>
              <div style="height: 18px;">
                <label class="detail_label">{{ obj.nannong_type }}</label>
              </div>
              <div style="height: 18px;">
                <label class="detail_label">{{ obj.create_date }}</label>
              </div>

            </div>
          </el-card>
        </el-col>
      </el-row>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import crudFarmNannong from '@/api/jf/farmNannong'
import CRUD, { presenter, header, form, crud } from '@crud/V2/crud'
import rrOperation from '@crud/V2/RR.operation'
import crudOperation from '@crud/V2/CRUD.operation'
import udOperation from '@crud/V2/UD.operation'
import pagination from '@crud/V2/Pagination'

const defaultForm = { id: null, farm_id: null, nannong_type: null, create_date: null }
export default {
  name: 'Equipment',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '图片数据', url: 'api/v2/base/farm/nannong', idField: 'id', sort: 'id,desc', crudMethod: { ...crudFarmNannong }})
  },
  dictsV2: ['farms'],
  dicts: ['equipment_type', 'eq_interface_type', 'nannong_type'],
  data() {
    return {
      showImageViewer: false,
      imageViewerId: '',
      fileList: [{ id: '001', name: 'food.jpeg', url: '/api/v2/public/getImage?id=11' }],
      uploadFilePop: false,
      uploadFileLoading: false,
      permission: {
        add: ['admin', 'farmNannong:add'],
        edit: ['admin', 'farmNannong:edit'],
        del: ['admin', 'farmNannong:del']
      },
      rules: {
        farm_id: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        create_date: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        nannong_type: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'farm_id', display_name: '所属农场' }
      ],
      fields: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created: function() {
    this.crud.optShow.download = false
    this.crud.optShow.edit = false
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      // console.log(form.images)
      this.fileList = []
      if (form.images != null) {
        for (let index = 0; index < form.images.length; index++) {
          const imageId = form.images[index]
          this.fileList.push({
            id: imageId,
            name: imageId,
            url: this.baseApi + '/api/v2/public/getImage?id=' + imageId
          })
        }
      }
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeValidateCU](crud) {
      // 检查并整理图片数据
      crud.form.newImages = []
      var files = this.$refs.upload.uploadFiles
      console.log('files', files)
      if (files.length < 1) {
        crud.notify('请上传图片!', CRUD.NOTIFICATION_TYPE.ERROR)
        return false
      }
      for (var i = 0; i < files.length; i++) {
        var file = files[i]
        if (files[i].hasOwnProperty('raw')) {
          var imglist = ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/gif']
          var isImage = imglist.some(function(item) {
            return item === file.raw.type
          })
          const isLt2M = file.raw.size / 1024 / 1024 < 1
          if (!isImage) {
            crud.notify('上传图片只能是图片格式!', CRUD.NOTIFICATION_TYPE.ERROR)
            return false
          }
          if (!isLt2M) {
            crud.notify('上传图片大小不能超过 1MB!', CRUD.NOTIFICATION_TYPE.ERROR)
            return false
          }
          crud.form.newImages.push(file.raw)
        }
      }
      // console.log(crud.form)
      // magic-api不支持数组参数，转为字符
      // crud.form.oldImages = crud.form.oldImages.toString()
      return true
    },
    [CRUD.HOOK.afterValidateCU](crud) {
      // console.log(crud.form)
      // return
    },
    [CRUD.HOOK.afterSubmit](crud) {
      this.fileList = []
    },
    [CRUD.HOOK.beforeAddCancel](crud) {
      this.fileList = []
    },
    [CRUD.HOOK.beforeEditCancel](crud) {
      this.fileList = []
    },
    handleShowImageViewer(imageId) {
      this.imageViewerId = imageId
      this.showImageViewer = true
    },
    selectedChange(obj) {
      var selections = []
      for (obj of this.crud.data) {
        if (obj.selected) {
          selections.push(obj)
        }
      }
      this.crud.selections = selections
    },
    cardClick(obj) {
      if (obj.selected) {
        obj.selected = false
      } else {
        obj.selected = true
      }
      this.selectedChange(obj)
    },
    skipOption(obj) {

    }
  }
}
</script>

<style scoped>
.image_wrap {
  display: flex;
  flex-flow: wrap;
  justify-content: flex-start;
  width: 1000px;
}
.imageCard {
  margin: 5px;
  flex: 1 0 180px;
  align-content: center;
}

.detail_label {
  text-align: right;
  vertical-align: middle;
  font-size: 14px;
  color: #606266;
  line-height: 30.5px;
}
</style>
